<?php
/**
 * Created by PhpStorm.
 * User: Love
 * Date: 2018/8/4
 * Time: 15:53
 */

namespace App\Http\Controllers\Admin;


use App\Admin;
use App\Exceptions\ServerException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;

/**
 * @property Admin model
 */
class AuthController extends Controller
{
    public function __construct(Admin $model)
    {
        $this->model = $model;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function login(Request $request)
    {
        $credentials = $request->only('nick_name','password');
        try{
            if (!$token = auth('admin')->attempt($credentials)){
                return $this->failed(400,"用户名或者密码错误");
            }
        }catch (JWTException $exception){
            throw new ServerException("JWTException");
        }
        $user = $this->model->where('nick_name',$credentials['nick_name'])->first();
        $this->model->where(['id'=>$user->id])->update(['ip'=>$request->ip(),'last_time'=>date('Y-m-d H:i:s')]);
        return $this->success(compact('token'));
    }
    public function test(Request $request)
    {
        $token = auth('admin')->attempt(['nick_name'=>'admins','password'=>'123']);
        $user = $this->model->find(2);
        $this->model->where(['id'=>$user->id])->update(['ip'=>$request->ip(),'last_time'=>date('Y-m-d H:i:s')]);
        return $this->success(compact('token'));
    }
    public function logout(){
        auth('admin')->logout();
        return $this->success();
    }
}